//
import vm from 'vm'
import { IPlugin } from '../bot/bot'

const sandbox: IPlugin = {
    name: '沙盒环境',
    onMessage(sender) {
        if (!sender.command || sender.command.name !== '/sandbox') return
        const code = sender.command.params.join(' ')
        try {
            // 禁止使用的模块，变量，语法
            const forbidden = [
                'require',
                'process',
                'global',
                'constructor',
                'try',
                'catch',
                'setTimeout',
                'setInterval',
                'eval',
            ]
            for (const word of forbidden) {
                if (code.includes(word)) {
                    sender.reply(`代码中包含禁止使用${word}`)
                    return
                }
            }
            const box = Object.create(null)
            const context = vm.createContext(box)
            const script = new vm.Script(code)
            const result = script.runInNewContext(context, { timeout: 5000 })
            sender.reply(`执行结果为：\n${result}`)
        } catch {
            sender.reply('代码执行失败')
        }
    },
}

export default sandbox
